﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Controllers;
using Common.Logging;
using In.Api.Dto.HisWs;
using Newtonsoft.Json;
using OutDbContext;
using User.Api.BizExtensions;
using User.Api.Dto.Doctor;
using User.Api.HttpClients;

namespace User.Api.Controllers
{
    public class DoctorController : ApiController
    {
        private static readonly ILog Logger = LogManager.GetLogger(typeof(DoctorController));
        private HzfyWeiXinEntities _ctx;

        protected override void Initialize(HttpControllerContext controllerContext)
        {
            _ctx = new HzfyWeiXinEntities();
            base.Initialize(controllerContext);
        }

        protected override void Dispose(bool disposing)
        {
            _ctx.Dispose();
            base.Dispose(disposing);
        }

        /// <summary>
        /// 获取医生信息，含医生的排班信息
        /// </summary>
        /// <param name="deptId">科室的院内编码</param>
        /// <param name="doctorId">医生的院内编码</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetByDoctorId")]
        public GetByDoctorIdResponse GetByDoctorId(string deptId, string doctorId)
        {
            var doctor = _ctx.Doctor.FirstOrDefault(x => x.DeptId == deptId && x.DoctorId == doctorId);

            if (doctor == null)
            {
                return new GetByDoctorIdResponse
                {
                    ResultCode = "1",
                    ResultMsg = "找不到医生"
                };
            }

            var res = new GetByDoctorIdResponse();
            res.DefaultSelectedDay = "无剩余号源";
            res.Today = DateTime.Now.ToString("yyyy-MM-dd");
            res.RegDays = new List<GetByDoctorIdResponse.ScheduleDay>();
            for (int i = 0; i < 8; i++)
            {
                res.RegDays.Add(new GetByDoctorIdResponse.ScheduleDay
                {
                    Date = DateTime.Now.AddDays(i).ToString("yyyy-MM-dd"),
                    IsFull = true,
                    TimeSlices = new List<GetByDoctorIdResponse.TimeSlice>()
                });
            }

            res.DeptId = deptId;
            res.DeptName = doctor.DepartName;
            res.DoctorId = doctorId;
            res.DoctorName = doctor.DoctorName;
            res.DoctorDesc = string.IsNullOrEmpty(doctor.Desc) ? "暂无介绍" : doctor.Desc;
            res.Sex = DoctorExtensions.ToZhSex(doctor.Gender);
            res.Title = doctor.Title;

            // 获取排班
            var request = new GetScheduleInfoRequest();
            request.DeptId = deptId;
            request.DoctorId = doctorId;
            request.BeginDate = DateTime.Now.ToString("yyyy-MM-dd");
            request.EndDate = DateTime.Now.AddDays(7).ToString("yyyy-MM-dd");

            GetScheduleInfoResponse response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetScheduleInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetScheduleInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内排班Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                res.ResultCode = "2";
                res.ResultMsg = "获取排班超时";
                return res;
            }

            if (response.ResultCode != "0")
            {
                res.ResultCode = "3";
                res.ResultMsg = response.ResultDesc;
                return res;
            }

            var scheduleInfos = response.ScheduleList;

            foreach (var scheduleInfo in scheduleInfos)
            {
                var scheduleDay = res.RegDays.First(x => x.Date == scheduleInfo.RegDate);
                if (scheduleInfo.TotalCount == "不限号" || scheduleInfo.LeaveCount.ToInt32OrDefault() > 0)
                {
                    scheduleDay.IsFull = false;
                    if (res.DefaultSelectedDay == "无剩余号源")
                    {
                        res.DefaultSelectedDay = scheduleInfo.RegDate;
                    }
                }

                scheduleDay.TimeSlices.Add(new GetByDoctorIdResponse.TimeSlice
                {
                    DeptId = scheduleInfo.DeptId,
                    DeptName = scheduleInfo.DeptName,
                    DoctorId = scheduleInfo.DoctorId,
                    DoctorName = scheduleInfo.DoctorName,
                    Title = scheduleInfo.Title,
                    RegType = scheduleInfo.RegType,
                    SliceName = scheduleInfo.TimeSlice,
                    SliceStartTime = scheduleInfo.StartTime,
                    SliceEndTime = scheduleInfo.EndTime,
                    LeaveCount = scheduleInfo.LeaveCount.ToInt32OrDefault() < 0 ? 0 : scheduleInfo.LeaveCount.ToInt32OrDefault(),
                    TotalCount = scheduleInfo.TotalCount.ToInt32OrDefault(),
                    HasTimePoint = scheduleInfo.IsTimeFlag == "1",
                    RegFee = scheduleInfo.Fee.ToDecimalOrDefault(),
                    TreatFee = scheduleInfo.TreatFee.ToDecimalOrDefault(),
                    OtherFee = scheduleInfo.OtherFee.ToDecimalOrDefault(),
                    TotalFee = scheduleInfo.Fee.ToDecimalOrDefault() + scheduleInfo.TreatFee.ToDecimalOrDefault() + scheduleInfo.OtherFee.ToDecimalOrDefault()
                });
            }

            res.ResultCode = "0";
            res.ResultMsg = "";
            return res;
        }

        /// <summary>
        ///  获取排班分时信息
        /// </summary>
        /// <param name="deptId">科室的院内编号</param>
        /// <param name="doctorId">医生的院内编号</param>
        /// <param name="regDate">挂号日期</param>
        /// <param name="regType">号源类型</param>
        /// <param name="timeSlice">时段</param>
        /// <returns></returns>
        [HttpGet]
        [ActionName("GetScheduleTimePoints")]
        public GetScheduleTimePointsResponse GetScheduleTimePoints(string deptId, string doctorId, string regDate,
            string regType, string timeSlice)
        {
            var res = new GetScheduleTimePointsResponse();
            res.TimePoints = new List<GetScheduleTimePointsResponse.TimePoint>();

            //执行获取排班分时信息
            var request = new GetTimeRegInfoRequest();
            request.DeptId = deptId;
            request.DoctorId = doctorId;
            request.RegDate = regDate;
            request.RegType = regType;
            request.TimeSlice = timeSlice;

            GetTimeRegInfoResponse response;
            try
            {
                var httpClient = InHttpClient.GetClient();
                var responseMsg = httpClient.PostAsJsonAsync("HisWs/GetTimeRegInfo", request).Result;
                responseMsg.EnsureSuccessStatusCode();
                response = responseMsg.Content.ReadAsAsync<GetTimeRegInfoResponse>().Result;
            }
            catch (Exception ex)
            {
                Logger.ErrorFormat("调用院内排班分时Api出错,信息：{0}", JsonConvert.SerializeObject(ex));
                res.ResultCode = "1";
                res.ResultMsg = "获取排班分时信息超时";
                return res;
            }

            if (response.ResultCode != "0")
            {
                res.ResultCode = "2";
                res.ResultMsg = response.ResultDesc;
                return res;
            }

            res.ResultCode = "0";
            res.ResultMsg = "";
            res.TimePoints = response.TimeRegList.Select(x => new GetScheduleTimePointsResponse.TimePoint
            {
                StartTime = x.StartTime,
                EndTime = x.EndTime,
                TotalCount = x.TotalCount,
                LeaveCount = x.LeaveCount,
                SqNo = x.SqNo
            }).ToList();

            return res;
        }
    }
}
